import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import RegisterView from '../views/RegisterView.vue'
import ProfileView from '../views/ProfileView.vue'
import MembershipView from '../views/MembershipView.vue'
import { isLoggedIn } from '../services/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'home',
      component: HomeView,
    },
    {
      path: '/about',
      name: 'about',
      // route level code-splitting
      // this generates a separate chunk (About.[hash].js) for this route
      // which is lazy-loaded when the route is visited.
      component: () => import('../views/AboutView.vue'),
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView,
      // 如果已登录，重定向到首页
      beforeEnter: (to, from, next) => {
        if (isLoggedIn()) {
          next({ name: 'home' })
        } else {
          next()
        }
      }
    },
    {
      path: '/register',
      name: 'register',
      component: RegisterView,
      // 如果已登录，重定向到首页
      beforeEnter: (to, from, next) => {
        if (isLoggedIn()) {
          next({ name: 'home' })
        } else {
          next()
        }
      }
    },
    {
      path: '/profile',
      name: 'profile',
      component: ProfileView,
      // 需要登录才能访问
      beforeEnter: (to, from, next) => {
        if (isLoggedIn()) {
          next()
        } else {
          next({ name: 'login' })
        }
      }
    },
    {
      path: '/membership',
      name: 'membership',
      component: MembershipView,
      // 需要登录才能访问
      beforeEnter: (to, from, next) => {
        if (isLoggedIn()) {
          next()
        } else {
          next({ name: 'login' })
        }
      }
    },
  ],
})

export default router
